package org.example.contestb.util;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;
public class EmailUtil {
    // SMTP服务器地址
    private static final String SMTP_HOST = "smtp.qq.com"; // 替换为你的SMTP服务器地址
    private static final int SMTP_PORT = 587; // SMTP服务器端口号，一般为587

    // 发件人邮箱地址和密码（需要在你的邮箱服务商处开启SMTP服务，并生成授权码）
    private static final String EMAIL_USERNAME = "1260258530@qq.com"; // 发件人邮箱
    private static final String EMAIL_PASSWORD = "dngwrjmqrmylfgai"; // 发件人邮箱密码或授权码

    // 发送验证码邮件
    public static void sendEmail(String toEmail, String verificationCode) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(EMAIL_USERNAME, EMAIL_PASSWORD);
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(EMAIL_USERNAME));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
            message.setSubject("验证码邮件");
            message.setText("您的验证码是：" + verificationCode + "，请在有效期内使用。");

            Transport.send(message);

            System.out.println("验证码邮件已发送到：" + toEmail);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
